#include "NetworkClient.h"

// =====================================================================
//      PUBLIC
// =====================================================================

bool NetworkClient::Connect(const char *host, const int port)
{
    _sock_fd = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
    if(_sock_fd<0)
    {
        ApplicationLog::Print("NetworkClient::Connect - Error opening socket",ApplicationLog::FATAL);
        return false;
    }
    
    maxsock = _sock_fd+1;
    
    struct hostent *H = gethostbyname(host);

    struct sockaddr_in adr;

    adr.sin_family = AF_INET;
    adr.sin_port = htons(port);
    adr.sin_addr.s_addr = *((unsigned long *) H->h_addr );
    memset(adr.sin_zero,0,8);

    if ( connect(_sock_fd,(struct sockaddr *) &adr,sizeof(adr)) < 0 )
    {
        ApplicationLog::Print("NetworkClient::Connect - Error connecting to server",ApplicationLog::FATAL);
        return false;
    }
    
    ApplicationLog::Print("NetworkClient::Connect - Connected to server on port ",port,ApplicationLog::INFO);
    
    Initialize();
}

// :THREADED:
void NetworkClient::Send(NetworkMessage* msg)
{
    Network::Send(_sock_fd,msg);
}

// =====================================================================
//      PROTECTED
// =====================================================================

// @Override Network :THREADED:
void NetworkClient::PrepareSet()
{
    // add server socket into set
//    _sock_fd_mutex.Acquire();
    
    FD_SET(_sock_fd, &ready);
    
//    _sock_fd_mutex.Release();
}

// @Override Network :THREADED:
void NetworkClient::HandleActiveSockets()
{
    /* Handle new connection */
//    _sock_fd_mutex.Acquire();
    
    if(FD_ISSET(_sock_fd,&ready))
        HandleNewData(_sock_fd);
    
//    _sock_fd_mutex.Release();
}

// @Override Network :THREADED:
void NetworkClient::LostConnectionHandler(int target_sockfd)
{
    ApplicationLog::Print("NetworkClient - Lost connection to server. Terminating main loop",ApplicationLog::FATAL);
    
    QuitMainLoop();
}

